import {useSelector} from "react-redux";
import {Badge, Button, Input, message, notification, Popconfirm, Rate, Table, Tooltip} from "antd";
import React, {useEffect, useState} from "react";
import axios from "axios";
import {CheckOutlined} from "@ant-design/icons";
import './css/orderPage.css'

const OrderPage = () => {
    const user = useSelector((state) => state.user.user);
    const [api, contextHolder] = notification.useNotification();
    const [expandedRowKeys, setExpandedRowKeys] = useState([]);
    const [orders, setOrders] = useState([]);
    const [services, setServices] = useState([]);
    const [comments, setComments] = useState([]);
    const fetchServices = async () => {
        try {
            const response = await axios.get('http://localhost:5532/service');
            setServices(response.data.data);
        } catch (error) {
            console.error('Error fetching services:', error);
        }
    };
    const fetchOrders = async () => {
        try {
            axios.get(
                'http://localhost:5532/order/getByUserId',
                {params: {userId: user.id}}
            ).then(res => {
                const orders = res.data.data;
                setOrders(orders);
                const newComments = Object.fromEntries(
                    orders
                        .filter(order => order.review !== null)
                        .map(order => [order.review.appointmentId, order.review.comment])
                );
                setComments(newComments);
            })

        } catch (error) {
            console.error('Error fetching orders:', error);
        }
    };
    // 初始化钩子
    useEffect(() => {
        fetchServices().then(r => fetchOrders());
    }, [])

    const pay = (paymentId) => {
        axios.post('http://localhost:5532/payment/pay', {
            id: paymentId
        }).then(response => {
            if (response.data.code === 1) {
                fetchOrders()
            }
        }).catch(error => {
            console.error(error);
        });
    }
    const onRateChange = (value, review) => {
        review.rating = value;
        review.comment = comments[review.appointmentId];
        axios.post('http://localhost:5532/review', {
            id: review.id,
            appointmentId: review.appointmentId,
            rating: review.rating,
            comment: review.comment,
            userId: user.id
        }).then(response => {
            if (response.data.code === 1) {
                api['success']({
                    message: '评价成功',
                    description: '评价成功',
                    placement: 'topLeft',
                });
                fetchOrders()
            }
        }).catch(error => {
            console.error(error);
        });
    };
    const onReviewChange = (value, review) => {
        console.log(value)
        console.log(review.comment)
        // 在下标为order.appointmentId处设置值
        setComments(prevComments => {
            const newComments = {...prevComments};
            newComments[review.appointmentId] = value;
            return newComments;
        });
    }
    const onReviewEnter = (e, review) => {
        review.comment = e.target.value;
        axios.post('http://localhost:5532/review', {
            id: review.id,
            appointmentId: review.appointmentId,
            rating: review.rating,
            comment: review.comment,
            userId: user.id
        }).then(response => {
            if (response.data.code === 1) {
                api['success']({
                    message: '评价成功',
                    description: '评价成功',
                    placement: 'topLeft',
                });
                fetchOrders();
            }
        }).catch(error => {
            console.error(error);
        });

    };

    const confirm = order => {
        axios.put(`http://localhost:5532/appointment/nextStep`, {
            id: order.appointmentId,
            status: 'canceled'
        }).then(res => {
            fetchServices().then(r => fetchOrders());
        });
    };


    const columns = [
        {
            title: '订单编号',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '预约项目',
            dataIndex: 'appointment',
            key: 'appointment',
            width: 150,
            render: (appointment) => {
                let text = '待商家确认';
                let backgroundColor = '#1677ff'
                switch (appointment.status) {
                    case 'init':
                        text = '待商家确认';
                        break;
                    case 'confirmed':
                        text = '商家已确认';
                        break;
                    case 'completed':
                        text = '订单已完成';
                        break;
                    case 'canceled':
                        text = '已取消';
                        backgroundColor = 'red'
                        break;
                }
                return (
                    <Badge.Ribbon text={text} style={{top: '-20px'}}>
                        <>
                            {services.find(service => service.id === appointment.serviceId).name}
                        </>
                    </Badge.Ribbon>
                )
            }
        },
        {
            title: '总金额',
            dataIndex: 'totalPrice',
            key: 'totalPrice',
        },
        {
            title: '订单状态',
            dataIndex: 'paymentStatus',
            key: 'paymentStatus',
            render: (paymentStatus) => {
                let str1 = '';
                switch (paymentStatus) {
                    case 'init':
                        str1 = '初始化';
                        break;
                    case 'half_paid':
                        str1 = '部分支付';
                        break;
                    case 'paid':
                        str1 = '已支付';
                        break;
                    case 'canceled':
                        str1 = '已退单';
                        break;
                }

                return (
                    <>
                        {str1}
                    </>
                )
            }
        },
        {
            title: '评价',
            dataIndex: 'id', // review
            key: 'pj',
            width: '50%',
            render: (id) => {
                const order = orders.find(order => order.id === id);
                if (order.paymentStatus !== 'paid') {
                    return (
                        <>
                            订单完成后即可评价
                        </>
                    )
                }
                let review = order.review;
                let appointmentId = order.appointmentId;
                if (review === null) {
                    review = {
                        appointmentId: order.appointmentId,
                        rating: 0,
                        comment: ''
                    }
                }
                return (
                    <>
                        <Rate onChange={(value) => onRateChange(value, review)}
                              value={review.rating}/>
                        <Input
                            value={comments[appointmentId]}
                            onChange={(e) => onReviewChange(e.target.value, review)}
                            onPressEnter={(e) => onReviewEnter(e, review)}
                            placeholder="写点什么吧"
                        />
                    </>
                )
            }
        },
        {
            title: '',
            dataIndex: 'id',
            key: 'td',
            width: '10%',
            render: (id) => {
                const order = orders.find(order => order.id === id);
                const disabled = (order.paymentStatus === 'paid') ||  (order.paymentStatus === 'canceled');
                return disabled ? (
                    <Button onClick={() =>{}} color="danger" disabled block>退单</Button>
                ):(
                    <Tooltip title="未完成的订单随时都可以退单，定金会自动退还至您的账户">
                        <Popconfirm
                            title="退单确认"
                            description="您确定要退单吗？"
                            onConfirm={()=>confirm(order)}
                            onCancel={()=>{}}
                            okText="Yes"
                            cancelText="No"
                        >
                            <Button color="danger" variant={"text"} disabled={disabled} >退单</Button>
                        </Popconfirm>
                    </Tooltip>
                )
            }
        }
    ]

    const expandedRowRender = (record, index) => (
        <Table
            rowHoverable={true}
            rowClassName={'expand-row'}
            columns={[
                {
                    title: 'id',
                    dataIndex: 'id',
                    key: 'id',
                    render: (id) => (
                        <>
                            支付记录号：{id}
                        </>
                    )
                },
                {
                    title: '应支付金额',
                    dataIndex: 'amount',
                    key: 'amount',
                    render: (amount) => (
                        <>
                            {amount} ￥
                        </>
                    )
                },
                {
                    title: '支付状态',
                    dataIndex: 'status',
                    key: 'status',
                    render: (status, id) => (
                        <>
                            {status === 'success' &&
                                <Button color="green" variant="outlined" icon={<CheckOutlined/>}>
                                    已支付
                                </Button>}
                            {status === 'pending' &&
                                <Button color="primary" variant="solid" onClick={() => pay(id.id)}>
                                    待支付
                                </Button>}
                        </>
                    )
                },
            ]}
            dataSource={record.payments}
            showHeader={false}
            pagination={false}/>
    );

    const handleRowExpand = (expanded, record) => {
        const newExpandedRowKeys = expanded
            ? [...expandedRowKeys, record.id]
            : expandedRowKeys.filter(id => id !== record.id);
        setExpandedRowKeys(newExpandedRowKeys);

    };

    return (
        <div className={'main-container'}>
            <Table
                rowKey="id"
                columns={columns}
                dataSource={orders}
                expandable={{
                    expandedRowRender,
                    expandedRowKeys,
                    onExpand: handleRowExpand,
                }}
                pagination={false}
                sticky={true}
                rowHoverable={false}
            />
        </div>
    )
}
export default OrderPage